﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;

namespace ShopayServer.Http
{
    public class Server
    {
        // 监听地址 
        private string url;

        // 路由
        public Route route = new Route();

        public Server(string url)
        {
            this.url = url;
        }

        public void start()
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(url);

            // 开始监听
            try
            {
                listener.Start();
                Console.WriteLine("Listening");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            // 监听请求
            try
            {
                while (true)
                {
                    //获取一个客户端请求为止
                    HttpListenerContext context = listener.GetContext();
                    //将其处理过程放入线程池
                    System.Threading.ThreadPool.QueueUserWorkItem(listenerHttpClient, context);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                listener.Stop(); //关闭HttpListener
            }
        }

        public void listenerHttpClient(object obj)
        {
            // 转换类型
            HttpListenerContext context = obj as HttpListenerContext;

            // 执行路由
            route.handle(context.Request, context.Response);
        }
    }
}
